<template>
	<view class="container">
		<view class="content">
			<!-- 左侧：会员信息和搜索 -->
			<view class="left-side">
				<view class="search-box">
					<input type="text" placeholder="[F2]刷卡或输入卡号" class="search-input" v-model="card_number" />
					<button class="search-button" size="mini" @click="search">搜索</button>
				</view>
				<view class="button-group">
					<button class="add-button" size="mini" @click="showAddProjectModal"
						style="width: 100%;">新增项目</button>
					<button class="add-button" size="mini" @click="showAddCategoryModal"
						style="width: 100%;">新增分类</button>
				</view>

				<view class="cart-list">
					<view v-for="item in cart" :key="item.id" class="cart-item">
						<view class="item-details">
							<text>{{ item.name }}</text>
							<text>￥{{ item.price }}</text>
							<text>数量：{{ item.quantity }}</text>
						</view>
						<view class="item-controls">
							<button @click="decreaseQuantity(item)" size="mini">-</button>
							<button @click="increaseQuantity(item)" size="mini">+</button>
							<button @click="removeItemFromCart(item)" size="mini">删除</button>
						</view>
					</view>
				</view>
				<view style="color: darkred;">会员名称：{{ name }}</view>

				<view class="order-summary">
					
					<view class="" style="margin-left: 20px;margin-top: 15px;">
						<view class="summary-item">合计数量：{{ totalQuantity }}</view>
						<!-- <view class="summary-item">本单积分：{{ totalPoints }}</view> -->
						<view class="summary-item">会员余额：{{ account_balance }}</view>
					</view>
					<view class="" style="margin-right: 20px;margin-top: 15px;">
						<!-- <view class="summary-item">本单优惠：￥{{ totalDiscount }}</view> -->
						<view class="summary-item">合计金额：￥{{ totalAmount }}</view>
						<view class="summary-item">余额：￥{{ yue }}</view>
					</view>
				</view>
				<view class="button-group bottom-buttons">
					<button class="clear-button" size="mini" @click="clearCart">清空[Del]</button>
					<button class="charge-button" size="mini" @click="submitOrder">实收[F5]：￥{{ bal }}</button>
				</view>
			</view>

			<!-- 右侧：分段器 -->
			<view class="right-side">
				<uni-segmented-control :current="currentSegment" :values="['计次项目', '会员计卡日志']"
					@clickItem="onSegmentChange"></uni-segmented-control>
				<view v-if="currentSegment === 0" class="item-container">
					<!-- 计次项目展示 -->
					<view class="category-list">
						<view class="item-category" @click="selectCategory(0)">
							全部
						</view>
						<view class="item-category" v-for="category in categories" :key="category.id"
							@click="selectCategory(category)">
							{{ category.name }}
						</view>
					</view>
					<view class="item-list">
						<view class="item" v-for="getProject in getProjects" :key="getProject.id"
							@click="addItemToCart(getProject)">
							<view class="item-name">{{ getProject.name }}</view>
							<view class="item-price">￥{{ getProject.price }}/次</view>
						</view>
					</view>
				</view>
				<view v-if="currentSegment === 1">
					<!-- 已有计次项目展示 -->
					<table class="table" style="margin-top: 10px;">
						<thead>
							<tr>
								<th>项目名称</th>
								<th>单价</th>
								<th>数量</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="item in cardLogs" :key="item.id">
								<td>{{ item.project_name }}</td>
								<td>￥{{ item.price }}</td>
								<td>{{ item.quantity }}</td>
								
								<td><button @click="removeItemFromCart(item)">删除</button></td>
							</tr>
							<tr v-if="cart.length === 0">
								<td colspan="5" class="no-data">无数据</td>
							</tr>
						</tbody>
					</table>
				</view>
			</view>
		</view>

		<!-- 新增计次项目弹窗 -->
		<view v-if="showProjectModal" class="modal">
			<view class="modal-content">
				<view class="modal-header">
					<text>新增计次项目</text>
					<button @click="closeModal" size="mini" style="margin-left: 150px;">关闭</button>
				</view>
				<view class="modal-body">
					<view class="form-group">
						<label>项目名称：</label>
						<input type="text" v-model="newProject.name" placeholder="输入项目名称" class="input-field" />
					</view>
					<view class="form-group">
						<label>单价：</label>
						<input type="number" v-model="newProject.price" placeholder="输入单价" class="input-field" />
					</view>
					<view class="form-group">
						<label>类别：</label>
						<select v-model="newProject.category_id" class="input-field">
							<option v-for="category in categories" :key="category.id" :value="category.id">
								{{ category.name }}</option>
						</select>
					</view>
				</view>
				<view class="modal-footer">
					<button @click="addNewProject" class="add-button" size="mini" style="width: 100%;">添加</button>
				</view>
			</view>
		</view>

		<!-- 新增类别弹窗 -->
		<view v-if="showCategoryModal" class="modal">
			<view class="modal-content">
				<view class="modal-header">
					<text>新增类别</text>
					<button @click="closeModal" size="mini" style="margin-left: 180px;">关闭</button>
				</view>
				<view class="modal-body">
					<view class="form-group">
						<label>类别名称：</label>
						<input type="text" v-model="newCategory.name" placeholder="输入类别名称" class="input-field" />
					</view>
				</view>
				<view class="modal-footer">
					<button @click="addNewCategory" class="add-button" size="mini" style="width: 100%;">添加</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: "",
				card_number: "",//会员卡号
				name: "",//会员名称
				account_balance: 0,//会员余额
				
				currentSegment: 0, // 分段器当前索引
				categories: [],
				category_id: '',
				selectedItems: [],
				cart: [],
				showProjectModal: false, // 控制项目弹窗显示
				showCategoryModal: false, // 控制类别弹窗显示
				newProject: {
					name: '',
					price: 0,
					category_id: ''
				},
				newCategory: {
					name: ''
				},
				getProjects: [],
				cardLogs: [] ,// 存储会员计卡日志
				userInfo: {}
				
			};
		},
		computed: {
			totalQuantity() {
				return this.cart.reduce((sum, item) => sum + item.quantity, 0);
			},
			totalPoints() {
				return this.cart.reduce((sum, item) => sum + item.points, 0);
			},
			totalDiscount() {
				return this.cart.reduce((sum, item) => sum + item.discount, 0);
			},
			totalAmount() {
				return this.cart.reduce((sum, item) => sum + Number(item.total), 0);
			},
			yue() {
				var yue = Number(this.account_balance) - this.cart.reduce((sum, item) => sum + Number(item.total), 0);
				return yue;
			},
			bal() {
				
				var yue = Number(this.account_balance) - this.cart.reduce((sum, item) => sum + Number(item.total), 0);
				
				if (yue<0) {
					var bal = this.cart.reduce((sum, item) => sum + Number(item.total), 0) - Number(this.account_balance);
				} else{
					var bal = 0;
				}
				return bal;
			}
			
		},
		methods: {
			//会员搜索逻辑
			async search() {
				// 实现搜索逻辑
				const res = await this.$myRuquest({
					url: '/index/plugin.foreground/search_user',
					data: {
						"card_number": this.card_number,
					},
				});
				if (res.data.code == 200) {
					this.card_number=res.data.date.card_number,//会员卡号
					this.name=res.data.date.name,//会员名称
					this.account_balance=res.data.date.account_balance,//会员余额

					uni.showToast({
						title: res.data.info,
						duration: 5000,
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: res.data.info,
						duration: 3000,
						icon: 'none'
					});
				}
			},
			clearCart() {
				this.cart = [];
			},

			async submitOrder() {
					try {
						const res = await this.$myRuquest({
							url: '/index/plugin.foreground/submit_order',
							method: 'POST',
							data: {
								card_number: this.card_number,
								cart: this.cart,
								member_name: this.name,//会员名称
								totalQuantity: this.totalQuantity,
								totalPoints: 0,
								totalDiscount: 0,
								totalAmount: this.totalAmount,
								yue: this.yue,//余额
								bal: this.bal ,//p实收
								shop_id: this.userInfo.shop_id,
							},
						});
						if (res.data.code === 200) {
							uni.showToast({
								title: '提交成功',
								duration: 2000,
								icon: 'success'
							});
							this.clearCart();
							this.search();
						} else {
							uni.showToast({
								title: res.data.info,
								duration: 2000,
								icon: 'none'
							});
						}
					} catch (error) {
						uni.showToast({
							title: '提交失败',
							duration: 2000,
							icon: 'none'
						});
					}
				}

				,
			showAddProjectModal() {
				this.newProject = {
					name: '',
					price: 0,
					category_id: ''
				};
				this.showProjectModal = true;
			},
			showAddCategoryModal() {
				this.newCategory = {
					name: ''
				};
				this.showCategoryModal = true;
			},
			closeModal() {
				this.showProjectModal = false;
				this.showCategoryModal = false;
			},
			async addNewProject() {
				// 添加新项目逻辑
				const res = await this.$myRuquest({
					url: '/index/plugin.foreground/add_project',
					method: 'POST',
					data: {
						name: this.newProject.name,
						price: this.newProject.price,
						category_id: this.newProject.category_id,
					},
				});
				if (res.data.code === 200) {
					this.selectedItems.push({
						...this.newProject,
						id: Date.now()
					});
					this.closeModal();
					this.getItemsByCategory();
					
				}
			},
			async get_category_id(id) {
				const res = await this.$myRuquest({
					url: '/index/plugin.foreground/get_projects',
					method: 'POST',
					data: {
						category_id: id,
					},
				});
				if (res.data.code === 200) {
					this.getProjects = res.data.data;
				}
			},
			async addNewCategory() {
				// 添加新类别逻辑
				const res = await this.$myRuquest({
					url: '/index/plugin.foreground/add_category',
					method: 'POST',
					data: {
						name: this.newCategory.name,
					},
				});
				if (res.data.code === 200) {
					this.categories.push({
						...this.newCategory,
						id: Date.now()
					});
					this.closeModal();
					this.getItemsByCategory();
				}
			},
			selectCategory(category) {
				// 根据选择的分类获取项目
				this.selectedItems = this.getItemsByCategory(category.id);
			},
			addItemToCart(item) {
				const cartItem = this.cart.find(cartItem => cartItem.id === item.id);
				if (cartItem) {
					cartItem.quantity++;
					cartItem.total = cartItem.quantity * cartItem.price;
				} else {
					this.cart.push({
						...item,
						quantity: 1,
						total: item.price
					});
				}
			},
			removeItemFromCart(item) {
				const index = this.cart.findIndex(cartItem => cartItem.id === item.id);
				if (index !== -1) {
					this.cart.splice(index, 1);
				}
			},
			increaseQuantity(item) {
				item.quantity++;
				item.total = item.quantity * item.price;
			},
			decreaseQuantity(item) {
				if (item.quantity > 1) {
					item.quantity--;
					item.total = item.quantity * item.price;
				}
			},

			async getItemsByCategory(categoryId) {
				const res = await this.$myRuquest({
					url: '/index/plugin.foreground/get_projects',
					method: 'POST',
					data: {
						category_id: categoryId,
					},
				});
				if (res.data.code === 200) {
					this.getProjects = res.data.data;
				}
				return [];
			},
			onSegmentChange(e) {
				this.currentSegment = e.currentIndex;
			},
			//获取会员充次日志
			async getCategories() {
				const res = await this.$myRuquest({
					url: '/index/plugin.foreground/get_categories',
					method: 'POST',
					data: {
						name: '',
					},
				});
				if (res.data.code === 200) {
					this.categories = res.data.data;
					
				}
			},
			//获取会员充次日志
			async getCardLogs() {
			      const res = await this.$myRuquest({
			        url: '/index/plugin.foreground/get_card_logs',
			        method: 'GET',
			        data: {
			          card_number: this.card_number,
			        },
			      });
			      if (res.data.code === 200) {
			        this.cardLogs = res.data.data;
			      }
			    },
			checkLoginStatus() {
			  const token = uni.getStorageSync('token');
					
			  if (token) {
			  
				this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
			  } else {
			
				this.userInfo = {};
				this.$router.push('/pages/login/login');
			  }
			},
				
		},
		mounted() {
			this.getCategories();
			this.getItemsByCategory();
			this.getCardLogs();
		},
		created() {
		  this.checkLoginStatus();
		},
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.content {
		display: flex;
		flex: 1;
	}

	.left-side {
		flex: 1;
		background-color: #fff;
		padding: 20px;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		margin-right: 20px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.cart-list {
		flex: 1;
		overflow-y: auto;
		margin-top: 20px;
	}

	.cart-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 4px;
		margin-bottom: 10px;
	}

	.item-details {
		flex: 1;
	}

	.item-controls {
		display: flex;
		gap: 5px;
	}

	.order-summary {
		display: flex;
		justify-content: space-between;
		margin-top: auto;
		background-color: #f9f9f9;
		border-top: 1px solid #ddd;
		padding: 10px;
		border-radius: 4px;
	}

	.summary-item {
		font-size: 14px;
		color: #333;
	}

	.button-group.bottom-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}

	.clear-button,
	.charge-button {
		background-color: #4cd964;
		color: white;
		border: none;
		padding: 8px 16px;
		cursor: pointer;
		border-radius: 4px;
		flex: 1;
		margin: 5px;
	}

	.clear-button:hover,
	.charge-button:hover {
		background-color: #45c853;
	}

	.right-side {
		flex: 2;
		background-color: #fff;
		padding: 20px;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		box-sizing: border-box;
	}

	.search-box {
		display: flex;
		margin-bottom: 20px;
		
	}

	.search-input {
		flex: 1;
		padding: 13px;
		border: 1px solid #ddd;
		border-radius: 4px 0 0 4px;
		outline: none;
	}

	.search-button,
	.add-button {
		background-color: #4cd964;
		color: white;
		border: none;
		padding: 10px 20px;
		cursor: pointer;
		border-radius: 0 4px 4px 0;
		margin-left: 10px;
	}

	.search-button:hover,
	.add-button:hover {
		background-color: #45c853;
	}

	.form-group {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	label {
		width: 80px;
		color: #666;
		margin-right: 10px;
	}

	.input-field {
		flex: 1;
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
		outline: none;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}

	.bottom-buttons {
		margin-top: auto;
		display: flex;
		justify-content: space-between;
	}

	.clear-button,
	.charge-button {
		background-color: #4cd964;
		color: white;
		border: none;
		padding: 8px 16px;
		cursor: pointer;
		border-radius: 4px;
		flex: 1;
		margin: 5px;
	}

	.clear-button:hover,
	.charge-button:hover {
		background-color: #45c853;
	}

	.title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.table {
		width: 100%;
		border-collapse: collapse;
	}

	.table th,
	.table td {
		border: 1px solid #ddd;
		padding: 8px;
		text-align: center;
	}

	.no-data {
		text-align: center;
		color: #999;
		padding: 20px 0;
	}

	.item-container {
		display: flex;
	}

	.category-list {
		margin-top: 20px;
		flex: 1;
		background-color: #f5f5f5;
		padding: 10px;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		margin-right: 20px;
	}

	.item-category {
		margin-top: 20px;
		padding: 10px;
		background-color: #fff;
		border-radius: 4px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		margin-bottom: 10px;
		cursor: pointer;
	}

	.item-category:hover {
		background-color: #4cd;
	}

	.item-list {
		flex: 3;
		display: flex;
		flex-wrap: wrap;
	}

	.item {
		background-color: #ecf9ef;
		border: 1px solid darkgray;
		padding: 0px;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		margin: 10px;
		flex: 1 1 calc(33.333% - 20px);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.item:hover {
		background-color: #4cd;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-content {
		background: #fff;
		padding: 20px;
		border-radius: 8px;
		width: 300px;
	}

	.modal-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.modal-body {
		margin: 20px 0;
	}
</style>